
package com.iwhalecloud.bss.kite.cucc.spec.impl.query;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsService;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccOfferOriginalInfoCache;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.api.IQueryOfferService;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferRelCache;
import com.iwhalecloud.bss.kite.dataservice.entity.ObjectLabelRel;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferRelInfo;
import com.iwhalecloud.bss.kite.dataservice.mapper.other.OfferAttrValueMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.OfferAttrMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.OfferExtAttrMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.OfferLabelMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.OfferMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.spec.OfferRstrCfgMapper;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description> 商品查询 <br>
 *
 * @author huang.caibiao<br>
 * @version 1.0<br>
 * @taskId <br>
 * @date 2020-03-04 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.spec.inf <br>
 */
@Service("offerQueryService")
public class OfferQueryService implements IQueryOfferService {

    @Autowired
    private OfferMapper offerMapper;

    @Autowired
    private OfferAttrMapper offerAttrMapper;

    @Autowired
    private IGoodsService goodsService;

    /**
     * 根据销售品标识查询销售品
     *
     * @param offerId 联通入参为goodsSku
     * @return
     */
    @Override
    public Offer getOffer(String offerId) {
        Map goodsInfo = CuccOfferOriginalInfoCache.get(offerId);
        if (KiteMapUtils.isEmpty(goodsInfo)) {
            goodsInfo = goodsService.queryGoodsByOfferId(offerId);
        }
         
        if (KiteMapUtils.isNotEmpty(goodsInfo)) {
            return GoodsInfoTransfer.convertOffer(goodsInfo);
        }
        return offerMapper.selectByPrimaryKey(offerId);
    }

    @Override
    public String getOfferLimitCheck(String offerId) {
        OfferRstrCfgMapper offerRstrCfgMapper = SpringUtil.getBean(OfferRstrCfgMapper.class);
        return Optional.ofNullable(offerRstrCfgMapper.getOfferLimitCheck(offerId)).orElse("");
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<OfferAttr> listOfferAttrs(String offerId) {
        Map goodsInfo = CuccOfferOriginalInfoCache.get(offerId);
        if (KiteMapUtils.isEmpty(goodsInfo)) {
            goodsInfo = goodsService.queryGoodsByOfferId(offerId);
        }
        if (KiteMapUtils.isEmpty(goodsInfo)) {
            List<OfferRelInfo> offerRels = Lists.newArrayList();
            // 为空则认为是资费产品转成的可选包销售品，这里根据资费产品ID获取销售品ID
            offerRels.addAll(Optional.ofNullable(OfferRelCache.getAOfferListRelsByz(offerId, CoreDataOffer.OFF_0006_100000)).orElse(Lists.newArrayList()));
            offerRels.addAll(Optional.ofNullable(OfferRelCache.getAOfferListRelsByz(offerId, CoreDataOffer.OFF_0006_110000)).orElse(Lists.newArrayList()));
            if (KiteListUtils.isEmpty(offerRels)) {
                return Lists.newArrayList();
            }
            String aOfferId = offerRels.get(0).getaOfferId();
            goodsInfo = CuccOfferOriginalInfoCache.get(aOfferId);
            if (KiteMapUtils.isEmpty(goodsInfo)) {
                goodsInfo = goodsService.queryGoodsByOfferId(aOfferId);
            }
            if (KiteMapUtils.isEmpty(goodsInfo)) {
                return Lists.newArrayList();
            }
        }
        List<OfferAttr> offerAttrs = GoodsInfoTransfer.convertOfferAttrs(goodsInfo);
        //查数据库中的
        String catId = Optional.ofNullable((String) goodsInfo.get("cateId")).orElse("");
        List<OfferAttr> offerAttrConfigs = Lists.newArrayList();
        offerAttrConfigs.addAll(offerAttrMapper.listOfferAttrs(catId));
        offerAttrConfigs.addAll(offerAttrMapper.listOfferAttrs(offerId));

        // 过滤，防止重复set属性（-1的有可能会覆盖其他的）
        List<OfferAttr> offerAttrfilter = Lists.newArrayList();
        Map<String, List<OfferAttr>> offerAttrMap = KiteListUtils.groupBy(offerAttrConfigs, "fieldName");
        offerAttrMap.forEach((k, v) -> {
            // 先找offerId为销售品id的（目前数据库里没配置offerId为销售品id的，其实可以不判断）
            OfferAttr offerAttr = v.stream().filter(t -> KiteStringUtils.equals(t.getOfferId(), offerId)).findFirst().orElse(null);
            if (Objects.isNull(offerAttr)) {
                // 再找offerId为分类id的
                offerAttr = v.stream().filter(t -> KiteStringUtils.equals(t.getOfferId(), catId)).findFirst().orElse(null);
                if (Objects.isNull(offerAttr)) {
                    // 如果都没有再找-1的
                    offerAttr = v.stream().filter(t -> KiteStringUtils.equals(t.getOfferId(), "-1")).findFirst().orElse(null);
                }
            }
            if (Objects.nonNull(offerAttr)) {
                offerAttrfilter.add(offerAttr);
            }
        });

        //极简不再做产商品册没有的销售品属性配置，只做二次配置
        //if (!KiteListUtils.isEmpty(offerAttrfilter)) {
        //    offerAttrs.addAll(offerAttrfilter);
        //}
        //设置属性处理类
        for (OfferAttr attr : offerAttrs) {
            for (OfferAttr attrConfig : offerAttrConfigs) {
                if (attr.getFieldName().equals(attrConfig.getFieldName())) {
                    attr.setOfferAttrId(attrConfig.getOfferAttrId());
                    attr.setHandlerClass(Optional.ofNullable(attrConfig.getHandlerClass()).map((handlerClass) -> handlerClass).orElse("com.iwhalecloud.bss.kite.service.attr.handler.DefaultAttrHandler"));
                    attr.setAttrValueTypeId(attrConfig.getAttrValueTypeId());
                }
            }
        }
        return offerAttrs;
    }

    @Override
    public List<OfferAttr> listDisplayOfferAttrs(String offerId) {
        List<OfferAttr> offerAttrs = listOfferAttrs(offerId);
        return offerAttrs.stream().filter(oa -> KiteStringUtils.equals(oa.getShowType(), KeyConsts.PROD_ATTR_SHOW_TYPE_D)).collect(Collectors.toList());
    }

    @Override
    public List<OfferAttr> listOfferExtAttrs(String offerId) {
        OfferExtAttrMapper offerExtAttrMapper = SpringUtil.getBean(OfferExtAttrMapper.class);
        return offerExtAttrMapper.listOfferExtAttrs(offerId);
    }

    @Override
    public List<OfferAttrValue> listOfferAttrValues(String offerAttrId) {
        return SpringUtil.getBean(OfferAttrValueMapper.class).selectValidAttrValuesByOfferAttrId(offerAttrId);
    }

    @Override
    public List<ObjectLabelRel> listOfferLabels(String offerId) {
        OfferLabelMapper offerLabelMapper = SpringUtil.getBean(OfferLabelMapper.class);
        return offerLabelMapper.listOfferLabels(offerId);
    }

    @Override
    public int hasOfferLabel(String offerId, String labelId) {
        OfferLabelMapper offerLabelMapper = SpringUtil.getBean(OfferLabelMapper.class);
        return offerLabelMapper.hasOfferLabel(offerId, labelId);
    }

}
